<template>
    <PageTabelLayout>
        <template #pageHeader>
            <div class="search-form" v-if="pageData.headerShow">
                <a-form size="mini" :model="pageData" layout="inline">
                    <a-form-item label="仓库类型">
                        <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" @change="whChange" placeholder=""
                            v-model="searchData.whTypeName" allow-clear>
                            <a-option v-for="item in whTypeList" :value="item.typeName">
                                {{ item.typeName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="选择公司">
                        <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" @change="companyChange" placeholder=""
                            v-model="searchData.firm" allow-clear>
                            <a-option v-for="item in companyList" :value="item.id">
                                {{ item.typeName ? item.typeName + '-' + item.firmName : item.firmName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="仓库">
                        <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" placeholder="" v-model="searchData.wh"
                            @click="ckisPd" @change="isWhilist" allow-clear>
                            <a-option v-for="item in whList" :value="item.warehouseName">
                                {{ item.warehouseName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="拆分单号">
                        <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" placeholder="" v-model="searchData.wh"
                            @click="ckisPd" @change="isWhilist" allow-clear>
                            <a-option v-for="item in whList" :value="item.warehouseName">
                                {{ item.warehouseName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                </a-form>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="pageData.headerShow" @click="pageData.headerShow = false" :strokeWidth="2"
                        :size="18" />
                    <icon-double-down v-else @click="pageData.headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
            <div class="my-tool-bar">
                <Toolbar :items="['查询']" @select="selectHandler">
                </Toolbar>
            </div>
        </template>
        <template #pageTabel>
            <!-- <a-tabs   :justify="true">
                <a-tab-pane title="库存列表"> -->
            <a-table size="mini" :scrollbar="true" sticky-header @page-change="pagination.change" stripe :bordered="true"
                :columns="tableColumns" :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                v-model:selected-keys="selectedRowKeys" :loading="pageData.pageLoading" :data="table.dataList"
                :pagination="{ size: 'mini', current: pagination.page, pageSize: pagination.pageSize, total: pagination.total }"
                rowKey="id">
                <template #action="{ record }">
                    <a-space>
                        <a-button type="primary" size="mini" @click="isXiang(record)">详情</a-button>
                        <a-button type="primary" status="success" size="mini">
                            审核
                        </a-button>
                    </a-space>
                </template>
                <template #auditState="{ record }">
                    <!-- <a-button v-if="(record.auditState == 0)" type="primary" status="warning" size="mini"
                        disabled>待&nbsp;审&nbsp;核&nbsp;
                    </a-button>
                    <a-button v-if="(record.auditState == 2)" status="success" size="mini" disabled>审核通过</a-button>
                    <a-button v-if="(record.auditState == 1)" type="primary" size="mini" status="danger" disabled>审核驳回
                    </a-button> -->
                    <a-button status="success" size="mini" disabled>审核</a-button>
                </template>
            </a-table>
            <!-- </a-tab-pane>
            </a-tabs> -->
        </template>
        <!-- @ok="sicksOk" -->
        <a-drawer ok-text='返回' :hide-cancel="true" cancel-text='取消' :style="{ 'zIndex': 999 }" :mask-closable="false"
            :height="600" :visible="pageData.showAdd" unmountOnClose @ok="sicksNo" placement="bottom" @cancel="sicksNo">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <!-- <a-space>
                    <a-button size="mini" type="primary" @click="tjWlzl">新增</a-button>
                </a-space> -->
                <div style="height:10px ;"></div>
                <a-table :style="{
                    height: '100%',
                    marginTop: '10px'
                }" stripe :bordered="true" :scrollbar="true" :pagination="false" sticky-header :columns="tableColumns1"
                    :data="tableSjList">
                    <template #action="{ record }">
                        666
                    </template>
                    <template #action1="{ record }">
                        <a-button type="outline" size="mini" @click="deletWhsWl(record)">
                            <template #icon>
                                <icon-delete />
                            </template>
                            删除
                        </a-button>
                    </template>
                </a-table>
            </div>
        </a-drawer>
        <a-modal v-model:visible="visible" title="详情" :width="1200" :footer="false" :draggable="true">
            <a-table :style="{
                height: '500px',
                marginTop: '10px'
            }" stripe :bordered="true" :scrollbar="true" sticky-header :pagination="false" :columns="tableColumns1"
                :data="whListMingxs">
            </a-table>
        </a-modal>
        <a-modal v-model:visible="visible2" :on-before-ok="handleOk" @cancel="handleCancel">
            <template #title>
                包装打包
            </template>
            <a-space direction="vertical" fill>
                <div><span>货&nbsp;&nbsp;&nbsp;架:</span><a-select popup-container="html"  class="bacClass" v-model="isCgds"
                        :style="{ width: '300px' }" @search="cxCgisLists" @click="cxCgisList" @change="cxCgisLists21"
                        allow-search allow-clear>
                        <a-option v-for="item in cgListArray">{{ item.shelveName }}</a-option>
                    </a-select></div>
                <div><span>包装盒:</span><a-select popup-container="html"  class="bacClass" v-if="isCgds != ''" v-model="isCgds2"
                        :style="{ width: '300px' }" @click="cxCgisList2" allow-search allow-clear>
                        <a-option v-for="item in cgListArray2" :value="item.boxCode">{{ item.boxName }}</a-option>
                    </a-select>
                    <a-select popup-container="html"  class="bacClass" v-else disabled v-model="isCgds2" :style="{ width: '300px' }"
                        @click="cxCgisList2" allow-search allow-clear>
                        <a-option v-for="item in cgListArray2">{{ item.boxName }}</a-option>
                    </a-select>
                </div>
            </a-space>
        </a-modal>
    </PageTabelLayout>
</template>

<script lang="ts">
import { post, get } from "@/api/http";
import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
} from "@/hooks/table";

import { ref, reactive, h, watch } from "vue";
import Toolbar from "@/components/Toolbar.vue";

import PageTabelLayout from "@/components/pageTabelLayout.vue";
import TreeUtils from "@/utils/TreeUtils";

import WHService, { Warhouse, CompanyList, WhTypeField } from '@/service/wh'
import { Message, Modal } from "@arco-design/web-vue";
import { IconDoubleUp, IconDoubleDown, IconEdit, IconFindReplace, IconDelete } from "@arco-design/web-vue/es/icon";
import pagination from "@arco-design/web-vue/es/pagination";
import { table } from "console";
import { rowKey } from "element-plus/es/components/table-v2/src/common";



export default {
    name: "SplitOrderAudit",

    setup() {

        const whService = new WHService()
        const whList = ref<any[]>([])
        const whTypeList = whService.whTypeList

        const whTypeFieldList = whService.whTypeFieldList
        const treeUtils = new TreeUtils()
        const companyList: any = whService.companyList
        const searchData = reactive<{
            whTypeName: string;
            firm: string,
            firmName: string,
            wh: string,
        }>({
            firm: '',
            whTypeName: "",
            firmName: "",
            wh: '',
        });

        function doRefresh() {
            pageData.pageLoading = true;
            post({
                url: "wms/WarehousetypeFieldvalue/getStockByPage",
                data: {
                    "page": pagination.page,
                    "size": pagination.pageSize,
                    "warehouseTypeName": searchData.whTypeName,
                    "warehouseName": searchData.wh,
                    "firmId": searchData.firm,
                    "infoType": 0
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        table.dataList.forEach((item: any) => {
                            if (item['outStockNum'] == '' || item['outStockNum'] == null || item['outStockNum'] == undefined || item['outStockNum'] == 0) {
                                item['outStockNum'] = 0
                            }
                            if (item['shiftNum'] == '' || item['shiftNum'] == null || item['shiftNum'] == undefined || item['shiftNum'] == 0) {
                                item['shiftNum'] = 0
                            }
                            if (item['returnNum'] == '' || item['returnNum'] == null || item['returnNum'] == undefined || item['returnNum'] == 0) {
                                item['returnNum'] = 0
                            }
                        })
                        pagination.setTotalSize(data.total);
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false;
                });
        }



        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        let tableColumns: any = ref([])
        let tableColumns1: any = ref([])
        let tableListDatas = reactive({
            typeLesIds: 0
        })
        watch(() => whService.whTypeFieldList.value, () => {

            tableColumns.value = whService.whTypeFieldList.value.map((f: any) => {
                return {
                    dataIndex: f.englishName,
                    key: f.englishName,
                    title: f.chineseName,
                    slotName: f.englishName,
                    width: 150,
                    ls: f.ls,
                    dropState: f.dropState,
                    conditions: f.conditions
                }
            })
            tableColumns1.value = whService.whTypeFieldList.value.map((f: any) => {
                return {
                    dataIndex: f.englishName,
                    key: f.englishName,
                    title: f.chineseName,
                    slotName: f.englishName,
                    width: 150,
                }
            })
            tableColumns.value.unshift({
                dataIndex: 'orderNo',
                key: 'orderNo',
                title: '单据编号',
                width: 180
            },
                {
                    dataIndex: 'outStockNum',
                    key: 'outStockNum',
                    title: '出库数量',
                    width: 180
                },
                {
                    dataIndex: 'shiftNum',
                    key: 'shiftNum',
                    title: '转仓数量',
                    width: 180
                },
                {
                    dataIndex: 'returnNum',
                    key: 'returnNum',
                    title: '退货数量',
                    width: 180
                }

            )

            tableColumns1.value.unshift({
                dataIndex: 'orderNo',
                key: 'orderNo',
                title: '单据编号',
                width: 180
            },
                {
                    dataIndex: 'outStockNum',
                    key: 'outStockNum',
                    title: '出库数量',
                    width: 180
                },
                {
                    dataIndex: 'shiftNum',
                    key: 'shiftNum',
                    title: '转仓数量',
                    width: 180
                },
                {
                    dataIndex: 'returnNum',
                    key: 'returnNum',
                    title: '退货数量',
                    width: 180
                }
            )
            tableColumns.value.push(
                {
                    title: '审核状态',
                    fixed: "right",
                    slotName: 'auditState',
                    width: 100
                },
                {
                    title: '操作',
                    fixed: "right",
                    slotName: 'action',
                    width: 150
                }
            )
            tableColumns1.value.push(
                {
                    title: '拆分数量',
                    fixed: "right",
                    slotName: 'action',
                    width: 100
                },
                {
                    title: '操作',
                    fixed: "right",
                    slotName: 'action1',
                    width: 100
                }
            )
            whService.whTypeFieldList.value.forEach((item: any) => {
                tableListDatas[item.englishName] = ''
            })


        })


        const pageData = reactive<{
            showAdd: boolean
            sideTitle: string
            pageLoading: boolean
            headerShow: boolean

        }>({
            showAdd: false,
            sideTitle: "拆分",
            pageLoading: false,
            headerShow: true
        })

        // const addHandler = () => {
        //     if (searchData.whTypeName == '' || searchData.wh == '' || firm == ''||searchData.whType=='') {
        //         Message.error('请先选择主页仓库类型或选择公司或仓库和单据类型')
        //     } else {
        //         pageData.sideTitle = '新增出库单'
        //         pageData.showAdd = true
        //     }
        // }
        const selectHandler = () => {
            if (searchData.whTypeName == '' || searchData.wh == '' || searchData.firm == '') {
                Message.error('请先选择主页仓库类型或选择公司或仓库和单据类型')
            } else {
                doRefresh()
            }
        }
        const isList: any = ref(['查询'])
        const whChange = (value: any) => {
            if (value == '制具仓') {
                isList.value = ['查询', '打包']
            } else {
                isList.value = ['查询']
            }
            whList.value = []
            searchData.wh = ''
            searchData.firm = ''
        }
        watch(() => whService.whList.value, (o, n) => {


            whList.value = whService.whList.value
        })
        // 公司下拉框 改变
        const companyChange = (val: any) => {
            whList.value = []
            searchData.wh = ''
            whService.getWarhouseList(searchData.firm, searchData.whTypeName)
            companyList.value.forEach((items: any) => {
                if (items.id == searchData.firm) {
                    searchData.firmName = items.typeName ? items.typeName + '-' + items.firmName : items.firmName
                }
            })
        }

        let visible = ref(false)
        let whListMingxs = ref<any[]>([])
        const isHangshuju: any = ref()
        const isXiang = async (val: any) => {
            // const res: any = await whService.getWarhouseMinxList(val.orderNo, val.warehouseTypeName, val.warehouseName, val.firm)
            // if (res.code == 200) {
            //     whListMingxs.value = res.data
            //     visible.value = true
            // }
            pageData.showAdd = true
            isHangshuju.value = val
        }
        let tableSjList: any = ref([])
        const tjWlzl = () => {
            // tableListDatas.typeLesIds++
            tableSjList.value.push({ ...isHangshuju.value, typeLesIds: tableListDatas.typeLesIds++ })
            console.log(tableSjList.value)
        }
        const sicksOk = async () => {
            tableListDatas.typeLesIds = 0
            if (pageData.sideTitle == '新增出库单') {
                tableSjList.value.forEach((item: any) => {
                    item['warehouseTypeName'] = searchData.whTypeName
                    item['warehouseName'] = searchData.wh
                    item['firm'] = searchData.firm
                    item['infoType'] = 2
                })
                const res: any = await whService.addWarhouseMinxList(tableSjList.value)
                if (res.code == 200) {
                    tableSjList.value = []
                    doRefresh()
                    Message.success('添加成功')
                    pageData.showAdd = false
                } else {
                    Message.error(res.message)
                }
            } else if (pageData.sideTitle == '修改出库单') {
                tableSjList.value.forEach((item: any) => {
                    item['warehouseTypeName'] = searchData.whTypeName
                    item['warehouseName'] = searchData.wh
                    item['firm'] = searchData.firm
                    item['infoType'] = 2
                    item['orderNo'] = orderNos
                    item['createName'] = tableSjList.value[0].createName
                    item['createTime'] = tableSjList.value[0].createTime
                })
                let updataWhdataList = {
                    warehouseTypeName: searchData.whTypeName,
                    warehouseName: searchData.wh,
                    firm: searchData.firm,
                    updateInfo: tableSjList.value
                }
                const res: any = await whService.updataWarhouseMinxList(updataWhdataList)
                if (res.code == 200) {
                    orderNos = ''
                    tableSjList.value = []
                    doRefresh()
                    Message.success('修改成功')
                    pageData.showAdd = false
                } else {
                    Message.error(res.message)
                }
            }
        }
        const sicksNo = () => {
            tableListDatas.typeLesIds = 0
            tableSjList.value = []
            pageData.showAdd = false
        }
        let orderNos: any;
        const xingXg = async (val: any) => {
            orderNos = val.orderNo
            const res = await whService.getWarhouseMinxList(val.orderNo, val.warehouseTypeName, val.warehouseName, val.firm)
            if (res.code == 200) {
                tableSjList.value = res.data
                pageData.sideTitle = '修改出库单'
                pageData.showAdd = true
            }
        }

        const deletWh = (val: any) => {
            let objDelet = {
                warehouseTypeName: val.warehouseTypeName,
                warehouseName: val.warehouseName,
                firm: val.firm,
                delOrderNoInfo: [val.orderNo]
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk: async () => {
                    const res: any = await whService.deletWarhouseMinxList(objDelet)
                    if (res.code == 200) {
                        Message.success('删除成功')
                        doRefresh()
                    } else {
                        Message.error(res.message)
                    }
                }
            })
        }
        const deletWhsWl = (val: any) => {
            // let objDelet = {
            //     warehouseTypeName: val.warehouseTypeName,
            //     warehouseName: val.warehouseName,
            //     firm: val.firm,
            //     delInfo: [val.id]
            // }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                // onOk: async () => {
                //     if (val.id == undefined) {
                //         tableSjList.value.forEach((item: any, index: any) => {
                //             if (val.typeLesIds == item.typeLesIds) {
                //                 tableSjList.value.splice(index, 1)
                //             }
                //         })
                //         if (tableSjList.value.length == 0) {
                //             pageData.showAdd = false
                //         }
                //     } else {
                //         const res: any = await whService.deletWhmxWarhouseMinxList(objDelet)
                //         if (res.code == 200) {
                //             Message.success('删除成功')
                //             const resz: any = await whService.getWarhouseMinxList(val.orderNo, val.warehouseTypeName, val.warehouseName, val.firm)
                //             if (resz.code == 200) {
                //                 if (resz.data.length == 0) {
                //                     whListMingxs.value = resz.data
                //                     tableSjList.value = resz.data
                //                     doRefresh()
                //                     pageData.showAdd = false
                //                 } else {
                //                     whListMingxs.value = resz.data
                //                     tableSjList.value = resz.data
                //                 }
                //             }
                //         } else {
                //             Message.error(res.message)
                //         }
                //     }
                // }
                onOk: () => {
                    tableSjList.value.forEach((item: any, index: any) => {
                        if (val.typeLesIds == item.typeLesIds) {
                            tableSjList.value.splice(index, 1)
                        }
                    })
                }
            })
        }
        const ckisPd = () => {
            if (searchData.whTypeName == '' || searchData.firm == '') {
                Message.error('请先选择仓库类型和所属工厂')
                return
            }
        }
        const isWhilist = (whName: any) => {
            let isWhId;
            whList.value.forEach((item: any) => {
                if (whName == item.warehouseName) {
                    isWhId = item.id
                }
            })
            whService.loadWHTypeFieldList({ warehouseId: isWhId, showType: 0 })
        }
        const dabaos = () => {
            if (selectedRowKeys.value.length == 0) {
                Message.error('请勾选数据')
                return false
            }
            let isList: any = []
            selectedRowKeys.value.forEach((item: any) => {
                table.dataList.forEach((o: any) => {
                    if (item == o.id) {
                        isList.push(o)
                    }
                })
            })
            for (let i = 0; i < isList.length; i++) {
                for (let j = i + 1; j < isList.length; j++) {
                    if (isList[i].shelveName != isList[j].shelveName) {
                        Message.error('请选择相同布笼')
                        return false
                    }
                }
            }
            visible2.value = true
        }
        const visible2 = ref(false)
        const handleOk = async () => {
            if (isCgds.value == '' || isCgds2.value == '') {
                Message.error('请选择布笼包装盒')
                return false
            }
            let isWhId;
            whList.value.forEach((item: any) => {
                if (searchData.wh == item.warehouseName) {
                    isWhId = item.id
                }
            })
            let isDatas: any = []
            selectedRowKeys.value.forEach((i: any) => {
                table.dataList.forEach((o: any) => {
                    if (i == o.id) {
                        isDatas.push(o)
                    }
                })
            })
            const res: any = await post({
                url: 'wms/WarehousetypeFieldvalue/setStockBoxInfo',
                data: {
                    warehouseId: isWhId,
                    infos: isDatas,
                    shelveName: isCgds.value,
                    boxCode: isCgds2.value
                }
            })
            if (res.code == 200) {
                Message.success(res.message)
                return true
            } else {
                Message.error(res.message)
                return false
            }
        }
        const handleCancel = () => {
            isCgds.value = ''
            isCgds2.value = ''
            visible2.value = false
        }
        const isCgds: any = ref('')
        const cgListArray: any = ref([])
        const cxCgisLists = (val: any) => {
            let isWhId;
            whList.value.forEach((item: any) => {
                if (searchData.wh == item.warehouseName) {
                    isWhId = item.id
                }
            })
            cxs({ shelveName: val, warehouseId: isWhId })
        }
        const cxCgisList = () => {
            let isWhId;
            whList.value.forEach((item: any) => {
                if (searchData.wh == item.warehouseName) {
                    isWhId = item.id
                }
            })
            cxs({ shelveName: '', warehouseId: isWhId })
        }
        function cxs(val: any) {
            post({
                url: 'wms/shelve/getFieldValue',
                data: val
            }).then((res: any) => {
                if (res.code == 200) {
                    cgListArray.value = res.data
                }
            })
        }
        const isCgds2: any = ref('')
        const cgListArray2: any = ref([])

        const cxCgisList2 = () => {
            if (isCgds.value == '') {
                Message.error('请先选择布笼')
                return
            }
            cxs2({ shelveName: isCgds.value })
        }
        function cxs2(val: any) {
            post({
                url: 'wms/warehouseBox/getBoxByShelveNotnull',
                data: val
            }).then((res: any) => {
                if (res.code == 200) {
                    cgListArray2.value = res.data
                }
            })
        }
        const cxCgisLists21 = (val: any) => {
            isCgds2.value = ''
        }
        return {
            cxCgisLists21,
            cgListArray2,
            cxCgisList2,
            isCgds2,
            cgListArray,
            cxCgisList,
            cxCgisLists,
            isCgds,
            visible2,
            handleCancel,
            handleOk,
            isList,
            dabaos,
            isWhilist,
            ckisPd,
            tableColumns1,
            deletWhsWl,
            deletWh,
            xingXg,
            sicksNo,
            sicksOk,
            tableSjList,
            tableListDatas,
            tjWlzl,
            whListMingxs,
            isXiang,
            visible,
            companyChange,
            whChange,
            selectHandler,
            // addHandler,
            companyList,
            whList,
            whTypeList,
            selectedRowKeys,
            whTypeFieldList,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            searchData,
            isHangshuju,
        };
    },
    components: { PageTabelLayout }
};
</script>
<style scoped lang="less">
.headerStyle {
    width: 40%;
    display: flex;
    justify-content: space-between;
}
</style>
